import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-05-31
 * Time: 23:16
 */

class Love {
    public String from;
    public String to;
    public String love;

    @Override
    public String toString() {
        return "Love{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", love='" + love + '\'' +
                '}';
    }

    public Love() {
        //没有这个一定不行！！！
        //因为后续json构建Love对象需要用到无参的构造方法
    }

    public Love(String from, String to, String love) {
        this.from = from;
        this.to = to;
        this.love = love;
    }
}


@WebServlet("/love")
public class ShowLove extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    //private List<Love> list = new ArrayList<>();



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如果有输入操作互动的操作，在这里refresh是不合理的，因为写着写着就刷新了，体验不好
        // 所以在这里设置refresh没用！

        //转换为json字符串！
        List<Love> list =  load();
        String result = objectMapper.writeValueAsString(list);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(result);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Love love = objectMapper.readValue(req.getInputStream(), Love.class);


        save(love);
        //默认返回的就是200的空报文
    }

    private List<Love> load(){

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Loves?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("mmsszsd666");//这是俺的微信号，欢迎添加，相互学习！
        List<Love> list = new ArrayList<>();
        try {
            Connection connection = dataSource.getConnection();
            String sql = "select * from message;";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            //这里的Set并不是，对象为Love的Set集合，而是一个迭代器！
            ResultSet set = preparedStatement.executeQuery();
            //迭代他（是next方法而不是hasnext）

            while(set.next()) {
                String from = set.getString("from");
                String to = set.getString("to");
                String love = set.getString("love");
                list.add(new Love(from, to, love));
            }

            set.close();
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void save(Love love){
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Loves?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("mmsszsd666");//这是俺的微信号，欢迎添加，相互学习！
        try {
            Connection connection = dataSource.getConnection();
            String sql = "insert into message values(?, ?, ?);";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, love.from);
            preparedStatement.setString(2, love.to);
            preparedStatement.setString(3, love.love);
            preparedStatement.executeUpdate();

            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}














